<template>
  <div class="login-container">
    <div class="login-card">
      <h2>管理员登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-item">
          <label>用户名</label>
          <input v-model="username" placeholder="请输入用户名" />
        </div>
        <div class="form-item">
          <label>密码</label>
          <input type="password" v-model="password" placeholder="请输入密码" />
        </div>
        <button type="submit" :disabled="loading">{{ loading ? '登录中...' : '登录' }}</button>
      </form>
      <div class="tips">默认账号: admin 密码: admin123</div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const username = ref('')
const password = ref('')
const errorMessage = ref('')
const loading = ref(false)

const handleLogin = async () => {
  try {
    loading.value = true
    const response = await axios.post('/api/login', {
      username: username.value,
      password: password.value
    })
    
    if (response.data.success) {
      // 存储token和管理员信息到本地
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('adminInfo', JSON.stringify(response.data.admin))
      router.push('/dashboard')
    } else {
      errorMessage.value = response.data.message || '用户名或密码错误'
      setTimeout(() => {
        errorMessage.value = ''
      }, 3000)
    }
  } catch (error) {
    errorMessage.value = '网络错误，请稍后重试'
    console.error('Login error:', error)
    setTimeout(() => {
      errorMessage.value = ''
    }, 3000)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}
.login-card {
  width: 400px;
  padding: 20px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  background-color: white;
  border-radius: 8px;
}
.form-item {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.tips {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}
.error-message {
  color: #f56c6c;
  font-size: 12px;
  text-align: center;
  margin-top: 10px;
}
</style>